package admin

import (
	"chaowan/data_source"
	"chaowan/models"
	"chaowan/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

type FanshangsRBody struct {
	Data       []models.Fanshang `json:"data"`
	PageNo     int               `json:"pageNo"`
	PageSize   int               `json:"pageSize"`
	TotalCount int64             `json:"totalCount"`
	TotalPage  int64             `json:"totalPage"`
}

type FanshangsBody struct {
	Status   int    `json:"status"`
	Page     int    `json:"page"`
	Pagesize int    `json:"pagesize"`
	Name     string `json:"name"`
	Classify int64  `json:"classify" gorm:"classify"` // 1付钱 2付积分
	Paixu    int64  `json:"paixu"`
}

func Fanshangs(ctx *gin.Context) {
	request := FanshangsBody{}
	ctx.ShouldBind(&request)
	status := request.Status
	classify := request.Classify
	name := request.Name
	currentPage := request.Page
	pageSize := request.Pagesize
	paixu := request.Paixu
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Fanshang
	res := data_source.Db.Debug()
	if name != "" {
		res = res.Where("name like ?", "%"+name+"%")
	}
	if status > 0 {
		res = res.Where("status = ?", status)
	}
	if classify > 0 {
		res = res.Where("classify = ?", classify)
	}
	res = res.Model(&models.Fanshang{}).Count(&count)
	res = res.Limit(pageSize).Offset(offsetNum)
	if paixu == 0 {
		res = res.Order("id desc").Find(&users)
	} else if paixu == 1 {
		res = res.Order("price asc").Find(&users)
	} else if paixu == 3 {
		res = res.Order("price desc").Find(&users)
	}

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := FanshangsRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type FanshangBody struct {
	ID            int64   `json:"id" gorm:"id"`
	Name          string  `json:"name" gorm:"name"`
	Classify      int64   `json:"classify" gorm:"classify"` // 1付钱 2付积分
	Liushui       float64 `json:"liushui" gorm:"liushui"`   // 满多少参与，流水or积分
	Image         string  `json:"image" gorm:"image"`
	Ashang        float64 `json:"ashang" gorm:"ashang"`               // a赏比例
	Bshang        float64 `json:"bshang" gorm:"bshang"`               // b赏比例
	Cshang        float64 `json:"cshang" gorm:"cshang"`               // c赏比例
	Dshang        float64 `json:"dshang" gorm:"dshang"`               // d赏比例
	Originalprice float64 `json:"originalprice" gorm:"originalprice"` // 原价
	Price         float64 `json:"price" gorm:"price"`                 // 一发价格
	Fiveprice     float64 `json:"fiveprice" gorm:"fiveprice"`         // 五发价格
	Tenprice      float64 `json:"tenprice" gorm:"tenprice"`           // 十发价格
	Status        int64   `json:"status" gorm:"status"`               // 1正常 2下架
	Images        string  `json:"images" gorm:"images"`
	Usernum       int64   `json:"usernum" gorm:"usernum"`
	Daynum        int64   `json:"daynum" gorm:"daynum"`
	Danchou       int64   `json:"danchou" gorm:"danchou"`
	Cjimage       string  `json:"cjimage" gorm:"cjimage"`
	Sort          int64   `json:"sort" gorm:"sort"`
}

func Fanshangsadd(ctx *gin.Context) {
	request := FanshangBody{}
	ctx.ShouldBind(&request)
	usernum := request.Usernum
	daynum := request.Daynum
	name := request.Name
	danchou := request.Danchou

	sort := request.Sort
	image := request.Image
	images := request.Images
	classify := request.Classify
	liushui := request.Liushui
	ashang := request.Ashang
	bshang := request.Bshang
	cshang := request.Cshang
	dshang := request.Dshang
	originalprice := request.Originalprice
	price := request.Price
	fiveprice := request.Fiveprice
	tenprice := request.Tenprice
	cjimage := request.Cjimage
	gt := models.Fanshang{
		Danchou:       danchou,
		Usernum:       usernum,
		Daynum:        daynum,
		Images:        images,
		Name:          name,
		Image:         image,
		Classify:      classify,
		Liushui:       liushui,
		Ashang:        ashang,
		Bshang:        bshang,
		Cshang:        cshang,
		Dshang:        dshang,
		Originalprice: originalprice,
		Price:         price,
		Tenprice:      tenprice,
		Fiveprice:     fiveprice,
		Status:        2,
		Cjimage:       cjimage,
		Sort:          sort,
	}
	data_source.Db.Create(&gt)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Fanshangsupdate(ctx *gin.Context) {
	request := FanshangBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	usernum := request.Usernum
	danchou := request.Danchou
	daynum := request.Daynum
	name := request.Name
	image := request.Image
	classify := request.Classify
	liushui := request.Liushui
	ashang := request.Ashang
	bshang := request.Bshang
	cshang := request.Cshang
	dshang := request.Dshang
	originalprice := request.Originalprice
	price := request.Price
	fiveprice := request.Fiveprice
	tenprice := request.Tenprice
	images := request.Images
	cjimage := request.Cjimage
	sort := request.Sort
	//gt := models.Fanshang{
	//	Usernum:       usernum,
	//	Daynum:        daynum,
	//	Name:          name,
	//	Images:        images,
	//	Image:         image,
	//	Classify:      classify,
	//	Liushui:       liushui,
	//	Ashang:        ashang,
	//	Bshang:        bshang,
	//	Cshang:        cshang,
	//	Dshang:        dshang,
	//	Originalprice: originalprice,
	//	Price:         price,
	//	Tenprice:      tenprice,
	//	Fiveprice:     fiveprice,
	//}
	//data_source.Db.Where("id = ?", id).Updates(&gt)

	data_source.Db.Model(&models.Fanshang{}).Where("id = ?", id).Updates(map[string]interface{}{"usernum": usernum, "daynum": daynum, "name": name, "image": image, "images": images, "classify": classify, "liushui": liushui, "ashang": ashang, "bshang": bshang, "cshang": cshang, "dshang": dshang, "originalprice": originalprice, "price": price, "tenprice": tenprice, "fiveprice": fiveprice, "danchou": danchou, "cjimage": cjimage, "sort": sort})
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Fanshangsgrounding(ctx *gin.Context) {
	request := FanshangBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	status := request.Status
	if status == 1 {
		var fanshanggood []models.Fanshanggood
		data_source.Db.Where("fanshangid = ?", id).Find(&fanshanggood)
		if len(fanshanggood) == 0 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "商品总数错误，无法上架",
			})
			return
		}
		var zhuanpan models.Zhuanpan
		data_source.Db.Where("state = 1").Where("fanshangid = ?", id).First(&zhuanpan)
		if zhuanpan.ID == 0 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "未添加，无法上架",
			})
			return
		}
		var num int64
		var goodnum int64
		a := 1
		b := 1
		c := 1
		d := 1
		for _, v := range fanshanggood {
			if v.Classify == 1 {
				if a == 1 {
					num = num + 1
					a = 2
				}
			}
			if v.Classify == 2 {
				if b == 1 {
					num = num + 1
					b = 2
				}
			}
			if v.Classify == 3 {
				if c == 1 {
					num = num + 1
					c = 2
				}
			}
			if v.Classify == 4 {
				if d == 1 {
					num = num + 1
					d = 2
				}
			}
			goodnum = goodnum + v.Num
		}
		if goodnum == num*1000000 {
			data_source.Db.Model(&models.Fanshang{}).Where("id = ?", id).Update("status", status)
		} else {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "商品总数错误，无法上架",
			})
			return
		}

	} else if status == 2 {
		data_source.Db.Model(&models.Fanshang{}).Where("id = ?", id).Update("status", status)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Fanshanginfo(ctx *gin.Context) {
	request := FanshangBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var good models.Fanshang
	data_source.Db.Where("id = ?", id).First(&good)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    good,
		"msg":     "ok",
	})
	return
}

type FanshanggoodsRBody struct {
	Data       []models.Fanshanggoodsql `json:"data"`
	PageNo     int                      `json:"pageNo"`
	PageSize   int                      `json:"pageSize"`
	TotalCount int64                    `json:"totalCount"`
	TotalPage  int64                    `json:"totalPage"`
}

type FanshanggoodsBody struct {
	Page       int   `json:"page"`
	Pagesize   int   `json:"pagesize"`
	Fanshangid int64 `json:"fanshangid" gorm:"fanshangid"`
}

func Fanshanggoods(ctx *gin.Context) {
	request := FanshanggoodsBody{}
	ctx.ShouldBind(&request)
	fanshangid := request.Fanshangid
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var niudangoodsql []models.Fanshanggoodsql
	res := data_source.Db.Model(&models.Fanshanggood{}).Select("fanshanggood.*, goods.name, goods.image, goods.price").Joins("left join goods on goods.id = fanshanggood.goodid").Where("fanshanggood.fanshangid = ?", fanshangid)
	res.Model(&models.Fanshanggood{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&niudangoodsql)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := FanshanggoodsRBody{
		Data:       niudangoodsql,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type FanshanggoodBody struct {
	ID         int64 `json:"id" gorm:"id"`
	Goodid     int64 `json:"goodid" gorm:"goodid"`
	Classify   int64 `json:"classify" gorm:"classify"` // 1a赏 2b赏 3c赏 4d赏
	Fanshangid int64 `json:"fanshangid" gorm:"fanshangid"`
	Num        int64 `json:"num" gorm:"num"`
}

func Fanshanggoodadd(ctx *gin.Context) {
	request := FanshanggoodBody{}
	ctx.ShouldBind(&request)
	goodid := request.Goodid
	classify := request.Classify
	fanshangid := request.Fanshangid
	num := request.Num

	gt := models.Fanshanggood{
		Goodid:     goodid,
		Classify:   classify,
		Fanshangid: fanshangid,
		Num:        num,
	}
	data_source.Db.Create(&gt)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Fanshanggoodupdate(ctx *gin.Context) {
	request := FanshanggoodBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	goodid := request.Goodid
	classify := request.Classify
	fanshangid := request.Fanshangid
	num := request.Num
	gt := models.Fanshanggood{
		Goodid:     goodid,
		Classify:   classify,
		Fanshangid: fanshangid,
		Num:        num,
	}
	data_source.Db.Where("id = ?", id).Updates(&gt)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Fanshanggooddel(ctx *gin.Context) {
	request := FanshanggoodBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	data_source.Db.Where("id = ?", id).Delete(&models.Fanshanggood{})
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

type ZhuanpanBody struct {
	ID            int64   `json:"id" gorm:"id"`
	Classify      int64   `json:"classify" gorm:"classify"` // 1积分 2赏卷
	Fanshangid    int64   `json:"fanshangid" gorm:"fanshangid"`
	Integral      int64   `json:"integral" gorm:"integral"`           // 积分数 classify =1 填写
	Shangjuanid   int64   `json:"shangjuanid" gorm:"shangjuanid"`     // 赏卷id  classify=2 选择
	Shangjuanname string  `json:"shangjuanname" gorm:"shangjuanname"` // 赏卷名称
	Num           int64   `json:"num" gorm:"num"`                     // 每次掉落几个隐藏奖
	Bili          float64 `json:"bili" gorm:"bili"`                   // 每次单抽获取的概率 10表示中奖概率百分之10
	Piaoping      string  `json:"piaoping" gorm:"piaoping"`           // 1a赏 2b赏 3c赏 3d赏
	Dengji        string  `json:"dengji" gorm:"dengji"`               // 1a赏 2b赏 3c赏 3d赏
	Qudao         string  `json:"qudao" gorm:"qudao"`                 // 渠道
	State         int64   `json:"state" gorm:"state"`                 // 1一番赏 2扭蛋机
}

func Zhuanpaninfo(ctx *gin.Context) {
	request := ZhuanpanBody{}
	ctx.ShouldBind(&request)
	fanshangid := request.Fanshangid
	state := request.State
	var zhuanpan models.Zhuanpan
	data_source.Db.Where("fanshangid = ?", fanshangid).Where("state = ?", state).First(&zhuanpan)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    zhuanpan,
		"msg":     "ok",
	})
	return
}
func Zhuanpanupdate(ctx *gin.Context) {
	request := ZhuanpanBody{}
	ctx.ShouldBind(&request)
	classify := request.Classify
	fanshangid := request.Fanshangid
	integral := request.Integral
	shangjuanid := request.Shangjuanid
	shangjuanname := request.Shangjuanname
	num := request.Num
	bili := request.Bili
	piaoping := request.Piaoping
	dengji := request.Dengji
	qudao := request.Qudao
	state := request.State
	var zhuanpan models.Zhuanpan
	data_source.Db.Where("fanshangid = ?", fanshangid).Where("state = ?", state).First(&zhuanpan)

	var zhuanpanid int64
	if zhuanpan.ID == 0 {
		zhuanpanup := models.Zhuanpan{
			Classify:      classify,
			Integral:      integral,
			Shangjuanid:   shangjuanid,
			Shangjuanname: shangjuanname,
			Num:           num,
			Bili:          bili,
			Piaoping:      piaoping,
			Dengji:        dengji,
			Qudao:         qudao,
			State:         state,
			Fanshangid:    fanshangid,
		}
		data_source.Db.Create(&zhuanpanup)
		zhuanpanid = zhuanpanup.ID
	} else {
		//data_source.Db.Where("id = ?", zhuanpan.ID).Debug().Updates(&zhuanpan)
		data_source.Db.Model(&models.Zhuanpan{}).Where("id = ?", zhuanpan.ID).Updates(map[string]interface{}{"classify": classify, "integral": integral, "shangjuanid": shangjuanid, "shangjuanname": shangjuanname, "num": num, "bili": bili, "piaoping": piaoping, "dengji": dengji, "qudao": qudao, "state": state, "fanshangid": fanshangid})

		zhuanpanid = zhuanpan.ID
	}
	data_source.Db.Where("zhuanpanid = ?", zhuanpanid).Delete(&models.Zhuanpanpiaoping{})
	if len(piaoping) > 0 {

		piaopingarr := strings.Split(piaoping, ",")
		var zppps []models.Zhuanpanpiaoping
		for _, p := range piaopingarr {
			zpppadd := models.Zhuanpanpiaoping{
				Zhuanpanid: zhuanpanid,
				State:      state,
				Otherid:    fanshangid,
				Piaoping:   utils.StrToInt64(p),
			}
			zppps = append(zppps, zpppadd)
		}
		data_source.Db.Create(&zppps)
	}
	data_source.Db.Where("zhuanpanid = ?", zhuanpanid).Delete(&models.Zhuanpandengji{})
	if len(dengji) > 0 {

		dengjiarr := strings.Split(dengji, ",")
		var zppps []models.Zhuanpandengji
		for _, p := range dengjiarr {
			zpppadd := models.Zhuanpandengji{
				Zhuanpanid: zhuanpanid,
				State:      state,
				Otherid:    fanshangid,
				Dengji:     utils.StrToInt64(p),
			}
			zppps = append(zppps, zpppadd)
		}
		data_source.Db.Create(&zppps)
	}
	data_source.Db.Where("zhuanpanid = ?", zhuanpanid).Delete(&models.Zhuanpanqudao{})
	if len(qudao) > 0 {
		qudaoarr := strings.Split(qudao, ",")
		var zppps []models.Zhuanpanqudao
		for _, p := range qudaoarr {
			zpppadd := models.Zhuanpanqudao{
				Zhuanpanid: zhuanpanid,
				State:      state,
				Otherid:    fanshangid,
				Qudaoid:    utils.StrToInt64(p),
			}
			zppps = append(zppps, zpppadd)
		}
		data_source.Db.Create(&zppps)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Qudaos(ctx *gin.Context) {

	var qudaos []models.Qudao
	data_source.Db.Order("id asc").Find(&qudaos)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    qudaos,
		"msg":     "ok",
	})
	return
}
